<?php

namespace app\common\entity;

use think\Db;
use think\Model;
use app\common\entity\Coindeals;
use app\common\entity\MywalletLog;
use app\common\entity\WithdrawRatio;
use think\facade\Log;
use app\common\entity\Config;

class OtcMatch extends Model
{
    protected $table = 'otc_match';

    protected $create_time = 'create_time';
    protected $matching_time = 'matching_time';
    protected $autoWriteTimestamp = true;
    /**
     * 买ta
     */
    static public function buyTa($market_id, $userId,$num) {
        $market = OtcMarket::where('id', $market_id)->find();
        if (!$market || $market->trade_type != 2) {
            throw new \Exception('对象不存在');
        }
        if ($market->status != 1) {
            throw new \Exception('订单已失效');
        }
        if ($market->user_id == $userId) {
            throw new \Exception('自己的订单不能买入哦');
        }

        /*if (OtcMarket::checkOrder($userId)) {
            throw new \Exception('你还有交易未完成');
        }*/
        if ($market['num'] < $num) {
            throw new \Exception('订单所剩余额'.$market['num']);
        }
        if ($market['min'] > $num) {
            throw new \Exception('交易最小额度'.$market['min']);
        }


        $entity = new self();
        $entity->uid = $market['user_id'];
        $entity->market_id = $market['id'];
        $entity->from_id = $userId;
        $entity->trade_type = 1;
        $entity->num = $num;
        $entity->price = $market['price'];
        $entity->total = bcmul($num,$market['price'],4);
        $entity->status = 1;
        $entity->create_time = time();
        $entity->charges = $market['charges'];
        $entity->pay_type = $market['pay_type'];
        $entity->order_number = self::order_number();
        $entity->pay_gyg = $num;

        if (!$entity->save()) {
            throw new \Exception('买入失败');
        }

        OtcMarket::where('id', $market_id)->setDec('num',$num);
        return $entity;
    }

    /**
     * 卖ta
     */
    static public function saleTa($market_id, $userId,$num,$pay_gyg) {
        $market = OtcMarket::where('id', $market_id)->find();
        if (!$market || $market->trade_type != 1) {
            throw new \Exception('对象不存在');
        }
        if ($market->status != 1) {
            throw new \Exception('订单已失效');
        }
        if ($market->user_id == $userId) {
            throw new \Exception('自己的订单不能买入哦');
        }

        /*if (OtcMarket::checkOrder($userId)) {
            throw new \Exception('你还有交易未完成');
        }*/
        if ($market['min'] > $num) {
            throw new \Exception('交易最小额度'.$market['min']);
        }
        if ($market['num'] < $num) {
            throw new \Exception('订单所需余额'.$market['num']);
        }
        $myGyg = Mywallet::where('user_id',$userId)->value('gyg');
        if ($myGyg < $num) {
            throw new \Exception('余额不足');
        }
        $entity = new self();
        $entity->uid = $userId;
        $entity->market_id = $market['id'];
        $entity->from_id = $market['user_id'];
        $entity->trade_type = 2;
        $entity->num = $num;
        $entity->price = $market['price'];
        $entity->total = bcmul($num,$market['price'],4);
        $entity->status = 1;
        $entity->create_time = time();
        $entity->charges = $market['charges'];
        $entity->pay_type = $market['pay_type'];
        $entity->order_number = self::order_number();
        $entity->pay_gyg = $pay_gyg;


        if (!$entity->save()) {
            throw new \Exception('买出失败');
        }
        $change = bcmul($market['charges'],0.01,4);
        OtcMarket::where('id',$market_id)->setDec('num',$num);

        return $entity;
    }

    static public function order_number(){
        $num = self::order('id desc')->value('id');
        if(!$num)$num = 0;
        return date('Ymd').$num+1;
    }

    static public function complete($id){
        $match = OtcMatch::where('id',$id)->find();
        $update = OtcMatch::where('id',$id)->update(['end_time'=>time(),'status'=>3,'success_time'=>time()]);
        if ($update) {
            MywalletLog::addLog($match['from_id'],$match['num'],1,'交易成功',6,1);
            $market = OtcMarket::where('id',$match['market_id'])->find();


            $change = bcmul($match['charges'],0.01,4);
            if($market['trade_type'] == 2){
                OtcMarket::where('id', $match['market_id'])->setDec('pay_gyg',bcmul($match['num'],1+$change,4));
            }else{
                OtcMarket::where('id', $match['market_id'])->setDec('pay_gyg',$match['num']);
            }
            self::profit($match['uid'],bcmul($match['num'],$change,2));
            $market = OtcMarket::where('id',$match['market_id'])->find();
            if($market['num'] <= 0){
                OtcMarket::where('id',$match['market_id'])->update(['status'=>2,'update_time'=>time(),'success_time'=>time()]);
            }
            return true;
        }
        return false;
    }

    static public function profit($uid,$number){
        $user = User::where('id',$uid)->find();
        #直推

        if($user['pid'] != 0){
            $zhitui = User::where('id',$user['pid'])->find();
            if($zhitui['is_close'] == 1){
                $num = bcmul($number,bcmul(UserLevelSend::getProfit($zhitui['level'],'trade'),0.01,4),4);

                MywalletLog::addLog($zhitui['id'], $num, 1, '交易手续费推荐奖', 9, 1);
            }
        }

        $users = User::select();
        foreach($users as $k=>$v){
            $platform = UserLevelSend::getProfit($v['level'],'platform');
            if($platform > 0 && $v['level'] == 5){
                $num = bcmul($number,bcmul($platform,0.01,4),4);

                MywalletLog::addLog($v['id'], $num, 1, '平台交易手续费加权平均', 9, 1);
                //lockToGyg($v['id'],$num,'平台交易手续费加权平均',2);
            }
        }
        return true;
    }


}
